package net.udp;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
import java.util.Set;

public class UDPEchoClientWithChannels
{
	public final static int DEFAULT_PORT = 7;
	public final static int LIMIT = 100;
	@SuppressWarnings("unused")
	public static void main(String[] args)
	{
		int port = DEFAULT_PORT;
		SocketAddress remote;
		try
		{
			remote = new InetSocketAddress("localhost",port);
		}
		catch (Exception e)
		{
		}
		try
		{
			DatagramChannel channel = DatagramChannel.open();
			channel.configureBlocking(false);
			Selector selector = Selector.open();
			channel.register(selector, SelectionKey.OP_READ|SelectionKey.OP_WRITE);
			ByteBuffer buffer = ByteBuffer.allocate(LIMIT);
			int n = 0;
			int numberRead = 0;
			while(true)
			{
				selector.select();
				Set<SelectionKey> selectedKeys = selector.selectedKeys();
				if(selectedKeys.isEmpty()&&n==LIMIT)
				{
					break;
				}else
				{
					Iterator<SelectionKey> iterator = selectedKeys.iterator();
					while(iterator.hasNext())
					{
						SelectionKey next = iterator.next();
						iterator.remove();
						if(next.isReadable())
						{
							buffer.clear();
							channel.read(buffer);
							buffer.flip();
							int echo = buffer.getInt();
							System.out.println(numberRead+echo);
							numberRead++;
						}
						if(next.isWritable())
						{
							buffer.clear();
							buffer.putInt(n);
							buffer.flip();
							channel.write(buffer);
							System.out.println(n);
							n++;
							if(n==LIMIT)
							{
								next.interestOps(SelectionKey.OP_READ);
							}
						}
						
					}
				}
			}
		}
		catch (Exception e)
		{
		}
	}
}
